//package com.zhuangjie.idworker.api.service;
//
//import com.zhuangjie.idworker.helper.SnowflakeHelper;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import javax.servlet.http.HttpServletRequest;
//import java.net.InetAddress;
//import java.net.UnknownHostException;
//
//@Service
//public class SnowflakeService {
//
//    @Autowired
//    private SnowflakeHelper snowflakeHelper;
//
//    public Long nextId(HttpServletRequest request) {
//        // 获取请求的 IP 地址
//        String clientIp = getClientIp(request);
//        // 检查是否为同一局域网
//        boolean isSameNetwork = isLocalAddress(clientIp);
//        if (! isSameNetwork) {
//            throw new RuntimeException("非法请求！");
//        }
//        return snowflakeHelper.nextId();
//    }
//
//    private static String getClientIp(HttpServletRequest request) {
//        String xForwardedForHeader = request.getHeader("X-Forwarded-For");
//        if (xForwardedForHeader == null) {
//            return request.getRemoteAddr();
//        } else {
//            // In a real-world scenario, you might need to handle multiple proxy servers.
//            // Here, we assume that the first IP in X-Forwarded-For is the client's IP.
//            return xForwardedForHeader.split(",")[0].trim();
//        }
//    }
//
//    private static boolean isLocalAddress(String ipAddress) {
//        try {
//            InetAddress inetAddress = InetAddress.getByName(ipAddress);
//            return inetAddress.isAnyLocalAddress() || inetAddress.isLoopbackAddress() || isPrivateAddress(inetAddress);
//        } catch (UnknownHostException e) {
//            // Handle exception (log, throw, etc.)
//            return false;
//        }
//    }
//
//    private static boolean isPrivateAddress(InetAddress inetAddress) {
//        // 判断是否为私有地址范围
//        byte[] addressBytes = inetAddress.getAddress();
//        return (addressBytes[0] == 10) ||
//                (addressBytes[0] == 172 && (addressBytes[1] >= 16 && addressBytes[1] <= 31)) ||
//                (addressBytes[0] == 192 && addressBytes[1] == 168);
//    }
//}
